package com.example.asyncio;

import cn.hutool.db.Entity;
import com.alibaba.fastjson.JSONObject;
import com.example.entity.Customer;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * Author wangJinLong
 * Date 2025/8/18 10:51
 **/
@Slf4j
public class DatabaseClient {
    private final ExecutorService executorService = Executors.newFixedThreadPool(5);

    public FutureTask<Customer> query(String query) {
        FutureTask<Customer> futureTask = new FutureTask<>(() -> {
            Thread.sleep(1500);
            log.info("DatabaseClient call..." + query);
            Customer customer = new Customer();
            customer.setFeaturesId(query);
            customer.setSiteSn("123");
            LocalDateTime now = LocalDateTime.now();
            long epochMilli = now.toInstant(ZoneOffset.systemDefault().getRules().getOffset(now)).toEpochMilli();
            customer.setCaptureTime(epochMilli);
            return customer;
        });

        new Thread(futureTask).start();

        return futureTask;
    }

    public FutureTask<Customer> queryAsyncDb(String key) {
        FutureTask<Customer> futureTask = new FutureTask<>(new Callable<Customer>() {
            @Override
            public Customer call() throws Exception {
                Entity first = DbApp.getMysqlDb()
                        .query("select * from spend_report where featuresId = ? limit 1", key)
                        .getFirst();

                Customer customer = new Customer();
                customer.setFeaturesId(first.getStr("featuresId"));
                customer.setSiteSn(first.getStr("siteSn"));
                customer.setCaptureTime(Long.parseLong(first.getStr("captureTime")));
                return customer;
            }
        });

        new Thread(futureTask).start();

        return futureTask;
    }

    public void close() {
        log.info("close database");
    }
}
